package com.yunxin.websitebox.website.realm;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunxin.websitebox.entity.WebsiteRole;
import com.yunxin.websitebox.entity.WebsiteUser;
import com.yunxin.websitebox.exception.UserBlockedException;
import com.yunxin.websitebox.exception.UserNotExistsException;
import com.yunxin.websitebox.service.WebsiteRoleService;
import com.yunxin.websitebox.service.WebsiteUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: lcj
 * @Date: 2020/10/12 17:26
 * @Description: 自定义Realm
 * @Version: 0.0.1
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {



    @Autowired
    private WebsiteUserService userService;
    @Autowired
    private WebsiteRoleService roleService;


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("Shiro授权....");
        WebsiteUser user = (WebsiteUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //查询角色信息
        Set<String> roles = new HashSet<String>();
        //查询菜单权限信息
        Set<String> perms = new HashSet<String>();

        List<WebsiteRole> websiteRoleList = roleService.selectRoleByUserId(user.getId());
        for(WebsiteRole websiteRole: websiteRoleList){
            roles.add(websiteRole.getRoleCode());
            try{
                JSONArray array = JSONArray.parseArray(websiteRole.getPerms());
                for(int i=0;i<array.size();i++){
                    JSONObject permObj = array.getJSONObject(i);
                    perms.add(permObj.getString("code"));
                }
            }catch (Throwable t){
                log.info("权限解析异常：{}",t);
            }
        }
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);
        return authorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("Shiro认证...");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        String username = userToken.getUsername();
        WebsiteUser user = null;
        try {
            user = userService.login(username);
        } catch (UserNotExistsException e) {
            throw new UnknownAccountException(e.getMessage(), e);
        } catch (UserBlockedException e) {
            throw new LockedAccountException(e.getMessage(), e);
        } catch (Exception e) {
            log.warn("验证用户[" + username + "]未通过!");
            throw new AuthenticationException(e.getMessage(), e);
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
        return authenticationInfo;
    }

    public static void main(String[] args) {
        SimpleHash simpleHash = new SimpleHash("MD5", "123456", "111111", 2);
        String encrypt = simpleHash.toString();
        System.out.println(encrypt);
    }
}
